package smartt.styy.auth.service.impl;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import smartt.styy.auth.constants.RedisConstants;
import smartt.styy.auth.service.VcodeManager;

@Service
public class VcodeManagerImpl implements VcodeManager {

	@Autowired
    private RedisTemplate<String, String> redisTemplate;

	@Override
	public String generateVcode() {
		return String.valueOf(new Random().nextInt(899999) + 100000);//生成短信验证码 短信验证码;
	}

	@Override
	public void saveVcode(String vCodePrefix,String mobile, String code, long expireTime, TimeUnit unit) {
		try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(vCodePrefix+RedisConstants.KEY_SPLIT+mobile, code);
            redisTemplate.expire(mobile, expireTime, unit);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

	@Override
	public Object getVcode(String vCodePrefix,String mobile) {
		Object result;
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        result = operations.get(vCodePrefix+RedisConstants.KEY_SPLIT+mobile);
        return result;
	}

	@Override
	public void removeVcode(String vCodePrefix,String mobile) {
		if(redisTemplate.hasKey(vCodePrefix+RedisConstants.KEY_SPLIT+mobile)){
            redisTemplate.delete(vCodePrefix+RedisConstants.KEY_SPLIT+mobile);
        }
	}
	
}
